package top.lingkang.finaloauth2.client.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import top.lingkang.finaloauth2.client.base.ResourceExceptionHandler;
import top.lingkang.finaloauth2.client.filter.ResourceServerFilter;
import top.lingkang.finaloauth2.client.http.ResourceHttpAccess;
import top.lingkang.finaloauth2.client.http.ResourceServerGetToken;
import top.lingkang.finaloauth2.client.http.ResourceServerHolder;
import top.lingkang.finaloauth2.client.http.ResourceServerHolderServices;
import top.lingkang.finaloauth2.utils.StringUtils;

import javax.annotation.PostConstruct;

/**
 * @author lingkang
 * Created by 2022/3/23
 */
public class ResourceServerConfiguration {
    private static final Log log = LogFactory.getLog(ResourceServerConfiguration.class);
    private ResourceServerProperties properties = new ResourceServerProperties();
    @Value("${final.oauth2.client.client-id:client_id}")
    private String clientId;
    @Value("${final.oauth2.client.secret:secret}")
    private String secret;
    @Value("${final.oauth2.client.scope:scope}")
    private String scope;
    @Value("${final.oauth2.client.server-url:http://localhost:8080}")
    private String serverUrl;

    protected void config(ResourceServerProperties properties) {

    }

    @PostConstruct
    private void init() {
        this.config(properties);
        if (StringUtils.isEmpty(properties.getClientId())) {
            properties.setClientId(clientId);
        }
        if (StringUtils.isEmpty(properties.getClientSecret())) {
            properties.setClientSecret(secret);
        }
        if (StringUtils.isEmpty(properties.getScope())) {
            properties.setScope(scope);
        }

        log.info("ResourceServer init finish!");
    }

    @Bean
    public ResourceServerProperties resourceServerProperties() {
        return properties;
    }

    @Bean
    public ResourceServerFilter resourceServerFilter() {
        return new ResourceServerFilter(properties);
    }

    @Bean
    public ResourceServerHolder resourceServerHolder() {
        if (!StringUtils.isEmpty(properties.getServerUrl())) {
            return new ResourceServerHolderServices(properties.getServerUrl());
        }
        return new ResourceServerHolderServices(serverUrl);
    }

    @Bean
    @ConditionalOnMissingBean
    public ResourceHttpAccess resourceHttpAccess() {
        return properties.getOauth2HttpAccess();
    }

    @Bean
    @ConditionalOnMissingBean
    public ResourceServerGetToken resourceServerGetToken() {
        return properties.getOauth2GetToken();
    }

    @Bean
    @ConditionalOnMissingBean
    public ResourceExceptionHandler resourceExceptionHandler() {
        return properties.getResourceExceptionHandler();
    }
}
